// 引入API模块
const { api } = require('../../utils/api');

// 格式化时间，兼容iOS
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  // 兼容后端返回的 "2025-05-11T01:51:56.000+00:00" 格式
  let str = timeStr.replace(/\.\d{3,}/, ''); // 去掉毫秒
  str = str.replace(/-/g, '/'); // 全部转为/
  str = str.replace('T', ' '); // T替换为空格
  str = str.replace(/\+\d{2}:?\d{2}$/, ''); // 去掉+00:00时区
  const date = new Date(str);
  if (isNaN(date.getTime())) return '';
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}`;
};

// 平铺转树工具，递归格式化时间和补全replyToUserName
function flatToTree(flat, parentId, idNameMap = {}) {
  // 构建id->userName映射
  (flat || []).forEach(r => {
    const userId = r.userId || (r.comment && r.comment.userId);
    const userName = r.userName || (r.comment && r.comment.userName);
    idNameMap[userId] = userName || '匿名用户';
  });
  
  // 格式化回复对象，确保格式一致
  const standardizeReply = (r) => {
    // 如果是 {comment:{...}, replies:[]} 格式转为标准回复格式
    if (r.comment) {
      return {
        id: r.comment.id,
        teacherId: r.comment.teacherId,
        userId: r.comment.userId,
        userName: r.comment.userName || '匿名用户',
        userAvatar: r.comment.userAvatar,
        content: r.comment.content,
        parentId: r.comment.parentId,
        createTime: formatTime(r.comment.createTime),
        replyToUserId: r.comment.replyToUserId,
        replyToUserName: r.comment.replyToUserName,
        replies: (r.replies || []).map(standardizeReply)
      };
    }
    
    // 已经是标准格式，格式化时间和补全replyToUserName
    return {
      ...r,
      createTime: formatTime(r.createTime),
      replyToUserName: r.replyToUserName || (r.replyToUserId ? idNameMap[r.replyToUserId] : '') || '匿名用户',
      replies: (r.replies || []).map(standardizeReply)
    };
  };
  
  // 标准化所有回复
  const standardized = (flat || []).map(standardizeReply);
  
  // 构建树
  const idMap = {};
  standardized.forEach(r => {
    r.replies = r.replies || [];
    idMap[r.id] = r;
  });
  
  const tree = [];
  standardized.forEach(r => {
    if (r.parentId && r.parentId !== parentId && idMap[r.parentId]) {
      if (!idMap[r.parentId].replies) {
        idMap[r.parentId].replies = [];
      }
      idMap[r.parentId].replies.push(r);
    } else if (r.parentId === parentId || r.parentId === null) {
      tree.push(r);
    }
  });
  
  return tree;
}

function mergeReplies(oldReplies, newReplies) {
  const map = {};
  oldReplies.forEach(r => { map[r.id] = r; });
  newReplies.forEach(r => {
    if (map[r.id]) {
      map[r.id].replies = mergeReplies(map[r.id].replies || [], r.replies || []);
    } else {
      oldReplies.push(r);
    }
  });
  return oldReplies;
}

Page({
  data: {
    teacher: {},
    comments: [],
    likeCount: 0,
    commentInput: '',
    page: 1,
    pageSize: 10,
    hasMore: true,
    isLoading: false,
    replyTo: null,
    replyToUserName: null,
    replyInput: '',
    replyPageSize: 2,
    parentId: null // 父评论ID
  },
  onLoad(options) {
    if (options.id) {
      const teacherId = options.id;
      this.loadTeacherDetail(teacherId);
      this.loadComments(teacherId);
    }
  },
  
  // 加载讲师详情
  async loadTeacherDetail(teacherId) {
    wx.showLoading({
      title: '加载中',
    });
    
    try {
      const res = await api.getTeacherDetail(teacherId);
      if (res.code === 200 && res.data) {
        this.setData({
          teacher: res.data,
          likeCount: res.data.likeNumbers || 0
        });
      }
    } catch (error) {
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },
  
  // 加载评论
  async loadComments(teacherId, isLoadMore = false) {
    if (!teacherId || this.data.isLoading) return;
    
    this.setData({ isLoading: true });
    try {
      const params = {
        page: isLoadMore ? this.data.page : 1,
        size: this.data.pageSize
      };
      
      const res = await api.getTeacherComments(teacherId, params);
      if (res.code === 200) {
        // 格式化评论时间
        const formattedComments = res.data.comments.map(item => ({
          ...item,
          replyPage: 1, // 新增，每条评论的回复页码
          comment: {
            ...item.comment,
            createTime: formatTime(item.comment.createTime)
          },
          replies: (item.replies || []).slice(0, this.data.replyPageSize).map(reply => ({
            ...reply,
            createTime: formatTime(reply.createTime)
          })),
          replyCount: item.replyCount || (item.replies ? item.replies.length : 0)
        }));
        
        const newComments = isLoadMore ? [...this.data.comments, ...formattedComments] : formattedComments;
        this.setData({
          comments: newComments,
          page: isLoadMore ? this.data.page + 1 : 2,
          hasMore: newComments.length < res.data.total,
          isLoading: false
        });
      }
    } catch (e) {
      this.setData({ isLoading: false });
    }
  },
  
  // 加载更多回复
  async loadMoreReplies(e) {
    const commentId = e.currentTarget.dataset.commentId;
    const { comments, replyPageSize } = this.data;
    const commentIndex = comments.findIndex(item => item.comment.id === commentId);
    if (commentIndex === -1) return;
    const currentPage = comments[commentIndex].replyPage || 1;
    
    try {
      const res = await api.getCommentReplies(commentId, {
        page: currentPage + 1,
        size: replyPageSize
      });
      
      if (res.code === 200 && res.data.comments && res.data.comments.length > 0) {
        // 直接处理新回复数据，不合并原有回复
        const standardizedNewReplies = (res.data.comments || []).map(reply => {
          if (reply.comment) {
            // 如果是 {comment:{...}, replies:[]} 结构，提取comment和replies
            return {
              ...reply.comment,
              createTime: formatTime(reply.comment.createTime),
              replies: (reply.replies || []).map(r => ({
                ...r,
                createTime: formatTime(r.createTime)
              }))
            };
          }
          return {
            ...reply,
            createTime: formatTime(reply.createTime)
          };
        });
        
        // 更新当前评论的回复列表
        const updatedComments = [...this.data.comments];
        updatedComments[commentIndex].replies = [
          ...updatedComments[commentIndex].replies,
          ...standardizedNewReplies
        ];
        updatedComments[commentIndex].replyPage = currentPage + 1;
        
        this.setData({
          comments: updatedComments
        });
      }
    } catch (error) {
      wx.showToast({
        title: '加载回复失败',
        icon: 'none'
      });
    }
  },
  
  // 滚动到底部加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadComments(this.data.teacher.id, true);
    }
  },
  
  // 点赞
  async onLike() {
    const teacherId = this.data.teacher.id;
    if (!teacherId) return;
    
    try {
      const res = await api.likeTeacher({id: teacherId});
      if (res.code == 200) {
        this.setData({
          likeCount: this.data.likeCount + 1
        });
        wx.showToast({ title: '点赞成功' });
      }else {
        wx.showToast({ title: res.message, icon: 'none' });
      }
    } catch (error) {
      wx.showToast({ title: '点赞失败', icon: 'none' });
    }
  },
  
  // 评论输入
  onCommentInput(e) {
    this.setData({ commentInput: e.detail.value });
  },
  
  // 回复输入
  onReplyInput(e) {
    this.setData({ replyInput: e.detail.value });
  },
  
  // 点击回复按钮
  onReply(e) {
    const { id, userName, parentId } = e.currentTarget.dataset;
    this.setData({
      replyTo: id,
      replyToUserName: userName || '匿名用户',
      parentId: parentId || id,
      replyInput: ''
    });
  },
  
  // 取消回复
  onCancelReply() {
    this.setData({
      replyTo: null,
      replyToUserName: null,
      parentId: null,
      replyInput: ''
    });
  },
  
  // 发送评论或回复
  async onSendComment() {
    const { teacher, commentInput, replyInput, replyTo, parentId } = this.data;
    
    if (!teacher.id) {
      wx.showToast({ title: '讲师ID不存在', icon: 'none' });
      return;
    }
    
    // 检查是评论还是回复
    const isReply = !!replyTo;
    const content = isReply ? replyInput : commentInput;
    
    if (!content.trim()) {
      wx.showToast({ title: '请输入内容', icon: 'none' });
      return;
    }
    
    wx.showLoading({ title: '发送中' });
    
    try {
      let res;
      if (isReply) {
        // 发送回复
        res = await api.commentTeacher({
          teacherId: teacher.id,
          content,
          parentId,
          replyToId: replyTo
        });
      } else {
        // 发送评论
        res = await api.commentTeacher({
          teacherId: teacher.id,
          content
        });
      }
      
      if (res.code === 200) {
        // 重置输入框
        this.setData({
          commentInput: '',
          replyInput: '',
          replyTo: null,
          replyToUserName: null,
          parentId: null,
          page: 1,  // 重置页码
          hasMore: true  // 重置加载更多状态
        });
        
        // 重新加载评论
        await this.loadComments(teacher.id);
        
        wx.showToast({ title: '发送成功' });
      } else {
        wx.showToast({ title: res.message || '发送失败', icon: 'none' });
      }
    } catch (error) {
      console.log(error)
      wx.showToast({ title: '发送失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  }
}) 